#! python3
# encoding=utf-8

import serial
import threading
import time

class Uart:
    '''自定义串口库文件'''

    def __init__(self, port, baudrate, bytesize, stopbits, parity, receiveHandler = None) -> None: # 端口， 波特率， 数据位，停止位， 流控, 校验方式
        self.ser = serial.Serial(timeout = 5)
        self.ser.port = port
        self.ser.baudrate = baudrate
        self.ser.stopbits = stopbits
        self.ser.bytesize = bytesize

        if parity == 'NONE':
            self.ser.parity = serial.PARITY_NONE  # 设置当前的文本校验方式为 无校验
        elif parity == 'ODD':
            self.ser.parity = serial.PARITY_ODD  # 设置当前的文本校验方式为 奇校验
        elif parity == 'EVEN':
            self.ser.parity = serial.PARITY_EVEN  # 设置当前的文本校验方式为 偶校验
        elif parity == 'MARK':
            self.ser.parity = serial.PARITY_MARK  # 设置当前的文本校验方式为 固定值1
        elif parity == 'SPACE':
            self.ser.parity = serial.PARITY_SPACE  # 设置当前的文本校验方式为 固定值0
        else:
            return None
        
        self.receiveHandler = receiveHandler
    
    def receivedThread(self):
        # threading.Timer(0.1, self.recvdata).start()
        while True:
            try:
                num = self.ser.inWaiting()
                if  num > 0:
                    data = self.ser.read(num)  # 读取串口数据
                    print("Recived:%s\n" % data.hex())
                    if self.receiveHandler != None:
                        self.receiveHandler(list(data))
            except Exception:  # 如果发生错误
                self.ser.close()  # 关闭定时器，停止接收
                print("Error: Cound not read")
                return None
            time.sleep(0.2)
        
    def serialOn(self): 
        if self.ser.is_open:
            return -1
        self.ser.open()  # 开启串
        time.sleep(1)
        threading.Thread(target=self.receivedThread).start()

    # def recvdata(self):  # 数据接收
    #     # self.receivedThread()
    #     try:
    #         num = self.ser.inWaiting()  # 接收数据
    #     except Exception:  # 如果发生错误
    #         self.ser.close()  # 关闭定时器，停止接收
    #         print("Error: Cound not read")
    #         return None
    #     if num > 0:
    #         data = self.ser.read(num)  # 读取串口数据
    #         # print("%s\n" % data.hex(" "))
    #         if self.receiveHandler != None:
    #             self.receiveHandler(list(data))

    def sendData(self, data):  # 数据发送
        if self.ser.isOpen():  # 如果串口已经打开
            try:
                return self.ser.write(data)       # 发送数据,并返回发送字数
            except:
                pass

# from crc import crc
# if __name__ == "__main__":
#     uart = Uart("com3", 115200, 8, 1, "NONE")
#     uart.serialOn()
#     data = [0x01, 0x04, 0x00, 0x00, 0x00, 0x02]
#     ls = crc.crc16([0x01, 0x04, 0x00, 0x00, 0x00, 0x02], True)
#     data += ls
#     while True:
#         uart.sendData(data)
#         time.sleep(1)